//
//  UserInfoController.m
//  e租帮
//
//  Created by ZSMAC on 2017/8/7.
//  Copyright © 2017年 ZSMAC. All rights reserved.
//

#import "UserInfoController.h"
@interface UserInfoController ()<UIActionSheetDelegate,UINavigationControllerDelegate,UIImagePickerControllerDelegate> {
    UIImageView * headCircleView;
    UITextField *textF;

}
@end

@implementation UserInfoController
- (instancetype)init
{
    self = [super init];
    if (self) {
        self.hidesBottomBarWhenPushed=YES;
    }
    return self;
}
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    if (self.navigationController.navigationBarHidden) {
        self.navigationController.navigationBarHidden=NO;
    }
}
- (void)setNavBar {
    self.title=@"个人信息";
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setNavBar];
    headCircleView = [[UIImageView alloc] initWithFrame:CGRectMake(self.view.width/2-(105/2), 80, 105, 105)];
    headCircleView.backgroundColor=[UIColor whiteColor];
    headCircleView.userInteractionEnabled=YES;
    headCircleView.layer.cornerRadius=105/2;
    headCircleView.layer.masksToBounds=YES;
    headCircleView.layer.borderWidth=1;
    headCircleView.layer.borderColor=[themeColor CGColor];
    headCircleView.image=self.headerImage;
    UITapGestureRecognizer * tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapClicked)];
    [headCircleView addGestureRecognizer:tap];
    [self.view addSubview:headCircleView];
    
    
    textF = [[UITextField alloc] initWithFrame:CGRectMake(0, headCircleView.bottom+20, SCREEN_WIDTH, 50)];
    textF.font=Font(17);
    textF.textAlignment=NSTextAlignmentCenter;
    textF.placeholder=@"请输入昵称";
    textF.text=self.nikeName;
    [self.view addSubview:textF];
    
    UIButton * saveBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    saveBtn.frame=CGRectMake(30,SCREEN_HEIGHT-65-NavBarHeight, SCREEN_WIDTH-60, 50);
    saveBtn.layer.cornerRadius=10;
    saveBtn.layer.masksToBounds=YES;
    saveBtn.titleLabel.font=[UIFont boldSystemFontOfSize:16];
    [saveBtn setTitle:@"保存" forState:UIControlStateNormal];
    saveBtn.backgroundColor=themeColor;
    [saveBtn addTarget:self action:@selector(saveClicked) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:saveBtn];
}



#pragma mark 选择头像
- (void)tapClicked {
    //选择头像
    [self selectPhotos];
}

#pragma mark - select Photo Library
- (void)selectPhotos {
    UIActionSheet *choiceSheet = [[UIActionSheet alloc] initWithTitle:nil
                                                             delegate:self
                                                    cancelButtonTitle:@"取消"
                                               destructiveButtonTitle:nil
                                                    otherButtonTitles:@"拍照", @"从相册中选取", nil];
    choiceSheet.tag=100;
    [choiceSheet showInView:self.view];
}
//PickerImage完成后的代理方法
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info{
    //定义一个newPhoto，用来存放我们选择的图片。
    UIImage *newPhoto = [info objectForKey:@"UIImagePickerControllerEditedImage"];
    headCircleView.image=newPhoto;
    //关闭当前界面，即回到主界面去
    [self dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark UIActionSheetDelegate
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
        if (buttonIndex == 0) {
            // 拍照
            //        其实和从相册选择一样，只是获取方式不同，前面是通过相册，而现在，我们要通过相机的方式
            //        */
            UIImagePickerController *PickerImage = [[UIImagePickerController alloc]init];
            //获取方式:通过相机
            PickerImage.sourceType = UIImagePickerControllerSourceTypeCamera;
            PickerImage.allowsEditing = YES;
            PickerImage.delegate = self;
            [self presentViewController:PickerImage animated:YES completion:nil];
            
        } else if (buttonIndex == 1) {
            // 从相册中选取
            //初始化UIImagePickerController
            UIImagePickerController *PickerImage = [[UIImagePickerController alloc]init];
            //获取方式1：通过相册（呈现全部相册），UIImagePickerControllerSourceTypePhotoLibrary
            //获取方式2，通过相机，UIImagePickerControllerSourceTypeCamera
            //获取方方式3，通过相册（呈现全部图片），UIImagePickerControllerSourceTypeSavedPhotosAlbum
            PickerImage.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;//方式1
            //允许编辑，即放大裁剪
            PickerImage.allowsEditing = YES;
            //自代理
            PickerImage.delegate = self;
            //页面跳转
            [self presentViewController:PickerImage animated:YES completion:nil];
        }

    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
#pragma mark 保存
- (void)saveClicked {
    if (textF.text.length==0) {
        [ZSProgressHUD showDpromptText:@"请输入昵称"];
        return;
    }
    @WeakObj(self);
     [ZSProgressHUD showHUDShowText:@"正在保存..."];
    [MPublicManager uploadImage:headCircleView.image successfulBlock:^(NSString *urlStr) {
        [selfWeak upUser:urlStr];
    } errorBlock:^{
        [ZSProgressHUD showDpromptText:@"头像上传失败"];
    }];

}
- (void)upUser:(NSString *)headerUrl {
    @WeakObj(self);
    BmobUser * user = [BmobUser currentUser];
    //此处是更新操作
    BmobObject  *gameScoreChange = [BmobObject objectWithoutDataWithClassName:@"_User" objectId:user.objectId];
    [gameScoreChange setObject:textF.text forKey:@"nickname"];
    [gameScoreChange setObject:headerUrl forKey:@"headerUrl"];
    [gameScoreChange updateInBackgroundWithResultBlock:^(BOOL isSuccessful, NSError *error) {
        if (isSuccessful) {
            [ZSProgressHUD showSuccessfulAnimatedText:@"保存成功"];
            [selfWeak backClicked];
        } else {
           [ZSProgressHUD showDpromptText:@"保存失败"];
        }
    }];

}

- (void)backClicked {
    [self.navigationController popViewControllerAnimated:YES];
}
@end
